﻿using movie.tool.library.binding;
using movie.tool.module.http;
using movie.tool.module.local;
using movie.tool.module.response;
using System.Net.Http;
using System.Net.Http.Json;
using System.Security.Cryptography;
using System.Text;
using System.Windows;
using System.Linq;
using Newtonsoft.Json;
using System.IO;
using System;
using movie.tool.library.time;
using movie.tool.library.ui;
using movie.tool.module.film.ui;
using movie.tool.module.film.model;

namespace movie.tool.module.login
{
    public class LoginParam : NotifyPropertyChanged
    {
        private string phoneNumber;
        private string password;
        public string PhoneNumber
        {
            get { return phoneNumber; }
            set
            {
                phoneNumber = value;
                SendPropertyChanged(() => PhoneNumber);
            }
        }
        public string Password
        {
            get { return password; }
            set
            {
                password = value;
                SendPropertyChanged(() => Password);
            }
        }
    }
    /// <summary>
    /// LoginPage.xaml 的交互逻辑
    /// </summary>
    public partial class LoginPage : CommonPage
    {
        private static readonly NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();

        public LoginParam Param { get; private set; }
        private bool keepLogin;
        public bool KeepLogin {
            get => keepLogin;
            set
            {
                keepLogin = value;
                SendPropertyChanged(nameof(KeepLogin));
            }
        }
        private BusyInfo busyInfo;
        public BusyInfo BusyInfo
        {
            get => busyInfo;
            set
            {
                busyInfo = value;
                SendPropertyChanged(nameof(BusyInfo));
            }
        }
        public LoginPage()
        {
            InitializeComponent();
            Param = new LoginParam();
            BusyInfo = new BusyInfo();
        }

        private async void LoginClick(object sender, RoutedEventArgs e)
        {
            if (BusyInfo.Busy)
            {
                return;
            }
            try
            {
                BusyInfo.Busy = true;
                BusyInfo.DefaultMessage();
                Param.Password = Sha1(pwd.Password);
                HttpContent content = JsonContent.Create(Param);
                TokenInfo token = await HttpInvoker.PostAsync<TokenInfo>("userserver/users/token", content);
                if (token != null)
                {
                    if (KeepLogin)
                    {
                        //保存token到本地
                        token.Timestamp = TimeUtils.GetTimeStamp();
                        string json = JsonConvert.SerializeObject(token);
                        using (FileStream fs = File.Create("token.txt"))
                        {
                            fs.Write(Encoding.UTF8.GetBytes(json));
                        }
                    }
                    else
                    {
                        if (File.Exists("token.txt"))
                        {
                            File.Delete("token.txt");
                        }
                    }
                    TokenStorage.Token = token;
                    HttpInvoker.UpdateToken(token.Access_token);
                    MainWindow.ShowPage("/module/film/ui/MovieListPage.xaml");
                }
            }
            finally
            {
                BusyInfo.Reset();
            }
        }
        /// <summary>
        /// 计算sha1的值
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        private string Sha1(string data)
        {
            byte[] bytes = Encoding.UTF8.GetBytes(data);
            SHA1 sha = SHA1.Create();
            bytes = sha.ComputeHash(bytes);
            StringBuilder sb = new StringBuilder();
            return string.Join(null,bytes.Select(item => string.Format("{0:x2}",item)));
        }

        private void Page_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                if (File.Exists("token.txt"))
                {
                    string str = File.ReadAllText("token.txt");
                    TokenInfo token =JsonConvert.DeserializeObject<TokenInfo>(str, OperatorResponse.settings);
                    if(token != null)
                    {
                        if (token.NearExpired)
                        {
                            //重新登录
                            KeepLogin = true;
                        }
                        else
                        {
                            //不用登录了，之前的令牌还能用
                            TokenStorage.Token = token;
                            HttpInvoker.UpdateToken(token.Access_token);
                            MainWindow.ShowPage("/module/film/ui/MovieListPage.xaml");
                        }
                    }
                }
            }
            catch(Exception ex)
            {
                logger.Error("读取令牌文件失败,重新登录",ex);
            }
        }

        public static void DeleteTokenFile()
        {
            if (File.Exists("token.txt"))
            {
                File.Delete("token.txt");
            }
        }
    }
}
